package com.only4play.codegen.registry;

import com.only4play.codegen.spi.CodeGenProcessor;

import java.lang.annotation.Annotation;
import java.util.*;

/**
 * 通过SPI 加载所有的CodeGenProcessor 识别要处理的annotation标记类
 */
public class CodeGenProcessorRegistry {

    private static Map<String, ? extends CodeGenProcessor> PROCESSORS;

    private CodeGenProcessorRegistry() {
        throw new UnsupportedOperationException();
    }

    /**
     * 注解处理器要处理的注解集合
     *
     * @return
     */
    public static Set<String> getSupportedAnnotations() {
        return PROCESSORS.keySet();
    }

    /**
     * 获取注解对应的处理器
     *
     * @return
     */
    public static CodeGenProcessor find(String annotationClassName) {
        return PROCESSORS.get(annotationClassName);
    }

    /**
     * spi 加载所有的processor
     */
    public static void initProcessors() {
        final LinkedHashMap<String, CodeGenProcessor> map = new LinkedHashMap<String, CodeGenProcessor>();
        final ServiceLoader<CodeGenProcessor> processors = ServiceLoader.load(CodeGenProcessor.class, CodeGenProcessor.class.getClassLoader());
        for (CodeGenProcessor next : processors) {
            final Class<? extends Annotation> annotation = next.getAnnotation();
            map.put(annotation.getName(), next);
        }
        PROCESSORS = map;
    }
}
